package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper ,AdUser> implements AdUserService {
    /**
     * 后台登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //判断前端传过来的手机号密码是否为空
        if (StringUtils.isNotBlank(dto.getName()) && StringUtils.isNotBlank(dto.getPassword())){
            //如果不为空则与数据库中的用户表对比密码
              //查询数据库
            AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            if (adUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //用户名存在，从数据库获取盐值，比对密码
            String salt = adUser.getSalt();   //盐值
            String  pswd = dto.getPassword(); //前端传过来的密码
            String password = DigestUtils.md5DigestAsHex((pswd + salt).getBytes()); //根据MD5+盐生成密码
            //生成的密码和数据库存的密码比对
            if (!adUser.getPassword().equals(password)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //根据用户的id，生成token。
            Map<String,Object> map = new HashMap<>();
            adUser.setName("");
            adUser.setPassword("");
            map.put("user",adUser);
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            return ResponseResult.okResult(map);
        }
       return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
}







